<template>
  <div class="mq-outbox">
    <div class="mq-inbox" ref="box">
      <div
        class="mq-list"
        :style="note"
        v-for="(item, index) in announcements"
        :key="index"
        ref="list"
      >
        <span class="mq-uname"
          ><i class="el-icon-message-solid"></i>{{ item.title }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/common/api'
export default {
  name: 'marquee-left',
  data() {
    return {
      note: {
        backgroundSize: '20px 20px',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: '1%  50%',
      },
      nowTime: null,
      announcements: [],
    }
  },
  mounted() {
    this.getAnnouncementList()
  },
  beforeDestroy() {
    clearInterval(this.nowTime)
    this.nowTime = null
  },
  methods: {
    getAnnouncementList(page = 1) {
      api.getAnnouncementList(page, 5).then(
        (res) => {
          this.announcements = res.data.data.records
          setTimeout(() => {
            let item = this.$refs.list
            let len = this.announcements.length
            let arr = []
            let margin = this.getMargin(item[0])
            for (let i = 0; i < len; i++) {
              arr.push(item[i].clientWidth + margin)
            }
            this.disArr = arr
            this.moveLeft()
          }, 500)
        },
        () => {}
      )
    },
    getMargin(obj) {
      let marg = window.getComputedStyle(obj, null)['margin-right']
      marg = marg.replace('px', '')
      return Number(marg)
    },
    moveLeft() {
      let that = this
      let outbox = this.$refs.box
      let startDis = 0
      this.nowTime = setInterval(function() {
        startDis -= 0.5
        if (Math.abs(startDis) > Math.abs(that.disArr[0])) {
          that.disArr.push(that.disArr.shift())
          that.announcements.push(that.announcements.shift())
          startDis = 0
        } else {
        }
        outbox.style = `transform: translateX(${startDis}px)`
      }, 1000 / 60)
    },
  },
}
</script>

<style lang="scss" scoped>
.mq-outbox {
  overflow: hidden;
  height: 35px;
  background: #e8eaec;
  .mq-inbox {
    white-space: nowrap;
    border-radius: 4px;
    .mq-list {
      margin-right: 100px;
      display: inline-block;
      font-size: 14px;
      text-indent: 30px;
      line-height: 40px;
      .mq-uname {
        color: #ff8900;
      }
    }
  }
}
</style>
